<!--
 * @Description: 
 * @Author: ZachGmy
 * @Date: 2022-08-25 16:38:39
 * @LastEditors: ZachGmy
 * @LastEditTime: 2022-08-25 16:49:52
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入qs -->
  <script src="./qs.js"></script>
</head>
<body>
  <!-- 输入框 -->
  <input type="text" name="" id="inp">
  <!-- 获取数据的按钮 -->
  <button onclick="getWeatherData()">获取天气数据</button>
  <script>
    // 获取用户输入的值
    var inp = document.getElementById('inp')
    var cityName;
    inp.oninput = function () {
      cityName = this.value
    }
    // https://api.muxiaoguo.cn/api/tianqi?city=长沙&type=1&api_key=779d7e46708290a5
    function getWeatherData() {
      var request = new XMLHttpRequest()
      // 第一种方式 拼接字符串
      // request.open('get','https://api.muxiaoguo.cn/api/tianqi?city=' + cityName + '&type=1&api_key=779d7e46708290a5')
      // 第二种方式 封装参数对象
      var params = {
        city: cityName,
        type: 1,
        api_key:'779d7e46708290a5'
      }
      
      request.open('get','https://api.muxiaoguo.cn/api/tianqi?' + Qs.stringify(params))
      request.send()
      request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
          console.log(request.responseText);
          var res = JSON.parse(request.responseText)
          console.log(res);
          alert(`${cityName}的温度是${res.data.temp}`)
        }
      }
    }
  </script>
</body>
</html>